﻿using System;
using System.Data.Entity;
using Castle.Core;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;

namespace Caramel.EntityFramework.Castle
{
	public class EntityFrameworkInstaller : IWindsorInstaller
	{
		public EntityFrameworkInstaller(DbContext context)
		{
			this.Context = context;
		}

		public DbContext Context { get; set; }

		public void Install(IWindsorContainer container, IConfigurationStore store)
		{
			container.
				Register(
					Component.
						For<DbContext>().
						Instance(this.Context).
						LifeStyle.
						Singleton,
					Component.
						For<IUnitOfWorkFactory>().
						UsingFactoryMethod(k => new EntityFrameworkUnitOfWorkFactory(k.Resolve<DbContext>())).
						LifeStyle.
						Singleton
				);

			container.
				Kernel.
				AddComponent(
					"__EntityFrameworkRepository__",
					typeof(IRepository<>), 
					typeof(EntityFrameworkRepository<>),
					LifestyleType.Singleton
				);
		}
	}
}
